import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/enter/son_material_dialog.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:material_collection_app/widget/enter/son_material_action_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../utils/utils.dart';

// 定义一个类继承于状态组件
class SonOutMaterialPage extends StatefulWidget {
  final Map arguments;

  SonOutMaterialPage({Key key, this.arguments}) : super(key: key);

  @override // 实例化
  State<StatefulWidget> createState() => MyOutMaterial();
}

class MyOutMaterial extends State<SonOutMaterialPage> {
  // 刷新
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  ScrollController listController = new ScrollController();
  // 变量定义
  var lastPage = 0;
  var currentPage = 1;
  int per_page = 20;
  var total = 0;
  int parentNum = 0;
  int d_num = 0;
  int y_num = 0;
  String baseApi = 'EnterMaterialSon/';
  int itemIndex = -1;
 

  // 子物资列表
  List sonList = [];
  // 物资选择数组
  List selectList = [];
  // 是否全选
  bool isSelectedAll = false;


  @override
  void initState() {
    super.initState();
    print(widget.arguments['list']);

    setState(() {
      sonList = widget.arguments['list'];
    });

    // getList(isInit: true);
  }


  // 创建按钮组件
  Widget _buildTopButtons() {
    return Column(
      children: <Widget>[
        Align(
          child: Container(
            height: 50,
            color: Utils.hexToColor('#297CFF'),
            padding: EdgeInsets.symmetric(horizontal: 10),
            // margin: EdgeInsets.only(bottom: 30.w),
            child: Row(
              children: [
                _buildTopButton(
                    '添加',
                    'add',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#33CCFF'),
                _buildTopButton(
                    '删除',
                    'del',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#990000'),
                _buildTopButton(
                    '修改备注',
                    'remark',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#66CC99'),
                _buildTopButton(
                    '修改数量',
                    'num',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#66CC99'),
                _buildTopButton(
                    '确认',
                    'confrim',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    '#66CC99')
              ],
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.all(10),
          child: Text(
            "主物资数量: ${parentNum} 已分配数量: ${y_num}待分配数量: ${d_num}",
            textAlign: TextAlign.start,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        )
      ],
    );
  }

  // 构建底部按钮
  Widget _buildTopButton(String title, String type, Alignment align,
      BorderRadius borderRadius, String color) {
    return Builder(builder: (BuildContext context) {
      return Align(
        alignment: align,
        child: GestureDetector(
            onTap: () {
              if (type == 'confrim') {
                // _confrimData();
                return;
              }

              if (type == 'add') {
                this.showAddMaterialDialog('add', numForm: {
                  'd_num': d_num,
                  'num': parentNum,
                  'y_num': y_num
                });
              } else {
                if (!sonList.any((element) => element['selected'] == true)) {
                  Utils.showText(text: '暂未选择物资');
                  return;
                }

                var ids = [];
                sonList.forEach((element) {
                  if (element['selected'] == true) {
                    ids.add({'id': element['id'], 'num': element['num']});
                  }
                });

                var numForm = {
                  'd_num': d_num,
                  'num': parentNum,
                  'y_num': y_num
                };

                if (type == 'num') {
                  showActionMaterialDialog('num',
                      title: '批量修改数量', ids: ids, numForm: numForm);
                }

                if (type == 'remark') {
                  showActionMaterialDialog('remark',
                      title: '修改备注', ids: ids, numForm: numForm);
                }

                if (type == 'del') {
                  this.delMaterial();
                }
              }
            },
            child: Container(
              child: Text(
                title,
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Utils.hexToColor('#ffffff')),
              ),
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
              decoration: BoxDecoration(
                  color: Utils.hexToColor(color),
                  borderRadius: BorderRadius.all(Radius.circular(4.0))),
              margin: EdgeInsets.only(right: 10),
            )),
      );
    });
  }

  // 构建按钮
  Widget _buildPage() {
    return Container(
      color: Utils.hexToColor('#F5F6FA'),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
              flex: 1,
              child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: SingleChildScrollView(
                    child: _buildTable(),
                  ),
                ),
              )
        ],
      ),
    );
  }

  Widget _buildTable() {
    return DataTable(
      columns: [
        DataColumn(label: Text('序号')),
        DataColumn(label: Text('物资名称')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('子物资备注')),
        DataColumn(label: Text('子RFID')),
      ],
      rows: sonList
          .asMap()
          .keys
          .map((index) => DataRow(
              color: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                if (states.contains(MaterialState.selected))
                  return Utils.hexToColor('#FFFFFF');
                // Even rows will have a grey color.
                // if (index % 2 == 0) return Colors.grey.withOpacity(0.3);
                return Utils.hexToColor(
                    '#ECF3FE'); // Use default value for other states and odd rows.
              }),
              cells: [
                DataCell(Text("${index + 1}")),
                DataCell(Text("${sonList[index]['goods_name']}")),
                DataCell(Text("${sonList[index]['num']}")),
                DataCell(Text("${sonList[index]['goods_unit']}")),
                DataCell(Text("${sonList[index]['remark'] != null ? sonList[index]['remark'] : '' }")),
                DataCell(Text("${sonList[index]['rfid_code']}"))
              ],
              
              ))
          .toList(),
    );
  }

  // 构建表格
  // Widget _buildTable() {
  //   return PaginatedDataTable(
  //       header: Text(
  //         // "主物资数量: ${parentNum} 已分配数量: ${y_num}待分配数量: ${d_num}",
  //         'header',
  //         textAlign: TextAlign.start,
  //         maxLines: 1,
  //         overflow: TextOverflow.ellipsis,
  //         style: TextStyle(fontSize: 28.w),
  //       ),
  //       columns: [
  //         DataColumn(label: Text('序号')),
  //         DataColumn(label: Text('物资名称')),
  //         DataColumn(label: Text('数量')),
  //         DataColumn(label: Text('计量单位')),
  //         DataColumn(label: Text('子物资备注')),
  //         DataColumn(label: Text('子RFID')),
  //       ],
  //       source: _items,
  //       rowsPerPage: per_page,
  //       availableRowsPerPage: [15, 50, 100, 500],
  //       // onRowsPerPageChanged: (v) {
  //       //   setState(() {
  //       //     per_page = v;
  //       //   });
  //       //   getList();
  //       // },

  //       onPageChanged: (page) {
  //         print('onPageChanged:$page');

  //         // setState(() {
  //         //   // currentPage = (total / (page + 1)).ceil();
  //         //   currentPage = 2;
  //         // });
  //         // print((total / (page + 1)).ceil());

  //         // getList();
  //       }
  //       );
  // }

  // 添加物资 || 编辑物资
  Future<void> showAddMaterialDialog(String type,
      {int itemInd, Map item, Map numForm}) async {
    if (type == 'edit') {
      setState(() {
        // updateStoresId = item['id'];
        itemIndex = itemInd;
      });
    }

    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: AddUpdateSonMaterialDialog(
                baseApi: baseApi,
                type: type,
                item: widget.arguments['item'],
                orderId: widget.arguments['id'],
                numForm: numForm,
                onSubmit: (e) {
                  print(e);
                  if (itemIndex != null) {
                    if (type == 'edit') {
                      // updateSingleMaterial(item['id']);
                    } else {
                      // getList(isInit: true);
                    }
                  }
                },
              ));
        });
  }

  // 添加物资 || 编辑物资
  Future<void> showActionMaterialDialog(String type,
      {int itemInd, Map item, Map numForm, String title, List ids}) async {
   
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: SonMaterialAcionDialog(
                baseApi: baseApi,
                type: type,
                item: widget.arguments['item'],
                orderId: widget.arguments['id'],
                numForm: numForm,
                title: title,
                ids: ids,
                onSubmit: (e) {
                  print(e);
                  if (itemIndex != null) {
                    if (type == 'num') {
                      // updateSingleMaterial(item['id']);
                      // getList(isInit: true);
                    }

                    if (type == 'remark') {
                      // getList(isInit: true);
                    }
                  }
                },
              ));
        });
  }

  Future<void> delMaterial() async {
    Utils.openAlert('确定要删除吗？', context).then((confirm) {
      if (confirm) {
        var ids = [];
        sonList.forEach((element) {
          if (element['selected'] == true) {
            ids.add(element['id']);
          }
        });
        DioUtils.request('EnterMaterialSon/del',
            context: context,
            method: 'POST',
            params: {'ids': ids}, onSuccess: (res) {
          if (res['code'] == 1) {
            setState(() {
              sonList.removeWhere((element) => element['selected'] == true);
            });
          }
          Utils.showText(text: res['msg']);
        }, onError: (err) {});

        return true;
      } else {
        return false;
      }
    });
  }

  // 渲染视图
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
      appBar: TopBar(
        title: '子物资',
      ),
      body: SafeArea(
        child: Container(
          child: Column(
            children: <Widget>[
              // _buildTopButtons(),
              Expanded(child: _buildPage())
            ],
          ),
        ),
      ),
    );
  }
}

